<script setup>
import { ref, reactive } from "vue";
import {Iphone, Key, Lock, Message, User, UserFilled} from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import {GetRegisterAccount, SendVerificationCode} from "@/api/index.js";
import {ElMessage} from "element-plus";
import {aesCipher, desCipher} from "@/utils/crypto.js";
const router = useRouter();

const registerForm = reactive({
  username: "",
  password: "",
  phone_number: "",
  email: "",
  user_type: "TESTER",
  code: "", // 验证码
});
const registerFormRef = ref();
// 对数据进行校验
const registerFormRules = reactive({
  username: [
    {
      required: true,
      message: "请输入用户名",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
    {
      min: 6,
      message: "密码长度不能少于6位",
      trigger: "blur",
    },
  ],
  phone_number: [
    {
      required: true,
      message: "请输入手机号",
      trigger: "blur",
    },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  email: [
    {
      required: true,
      message: "请输入邮箱",
      trigger: "blur",
    },
    {
      type: "email",
      message: "请输入正确的邮箱格式",
      trigger: "blur",
    },
  ],
  code: [
    {
      required: true,
      message: "请输入验证码",
      trigger: "blur",
    },
    {
      len: 4,
      message: "验证码长度为4位",
      trigger: "blur",
    },
  ],
});

const handleSendCode = async () => {
  const phone = registerForm.phone_number;

  if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
    ElMessage.warning("请输入正确的手机号");
    return;
  }
  try {
    const res = await SendVerificationCode({ mobile: phone });
    if (res.status === 200) {
      ElMessage.success("验证码已发送,请在5分钟内完成注册！");
    }
    else {
      // 处理后端返回的错误信息
      if (typeof res.msg === 'object') {
        let errorMessages = [];
        for (const [field, errors] of Object.entries(res.msg)) {
          if (Array.isArray(errors)) {
            errorMessages.push(...errors);
          } else {
            errorMessages.push(errors);
          }
        }
        ElMessage.error(errorMessages.join('; '));
      } else {
        ElMessage.error(res.msg || "验证码发送失败");
      }
    }
  } catch (error) {
    console.log(error)
    // 处理网络错误或其他异常
    if (error.response && error.response.data) {
      const errorData = error.response.data;
      if (typeof errorData.msg === 'object') {
        let errorMessages = [];
        for (const [field, errors] of Object.entries(errorData.msg)) {
          if (Array.isArray(errors)) {
            errorMessages.push(...errors);
          } else {
            errorMessages.push(errors);
          }
        }
        ElMessage.error(errorMessages.join('; '));
      } else {
        ElMessage.error(errorData.msg || "网络出错，请稍后重试");
      }
    } else {
      ElMessage.error("网络出错，请稍后重试");
    }
  }
};

const submitForm = async (registerFormRef) => {
  if (!registerFormRef) return ;
  await registerFormRef.validate(async (valid) => {
    if (valid) {
      await handleGetRegisterAccount()
    }
  })
}
const handleGetRegisterAccount = async () =>{
  try {
    // 对密码进行 AES 加密
    const encryptedPassword = aesCipher.aesEncrypt(registerForm.password);
    const formData = {
      ...registerForm,
      password: encryptedPassword, // 使用加密后的密码
    };
    const res = await GetRegisterAccount(formData)
    if( res.status===201){
      await router.push('/login')
      ElMessage.success(res.msg)
    }
    else{
      // 处理后端返回的错误信息
      if (typeof res.msg === 'object') {
        let errorMessages = [];
        for (const [field, errors] of Object.entries(res.msg)) {
          if (Array.isArray(errors)) {
            errorMessages.push(...errors);
          } else {
            errorMessages.push(errors);
          }
        }
        ElMessage.error(errorMessages.join('; '));
      } else {
        ElMessage.error(res.msg)
      }
    }
  } catch (error) {
    console.log(error);
    // 处理网络错误或其他异常
    if (error.response && error.response.data) {
      const errorData = error.response.data;
      if (typeof errorData.msg === 'object') {
        let errorMessages = [];
        for (const [field, errors] of Object.entries(errorData.msg)) {
          if (Array.isArray(errors)) {
            errorMessages.push(...errors);
          } else {
            errorMessages.push(errors);
          }
        }
        ElMessage.error(errorMessages.join('; '));
      } else {
        ElMessage.error(errorData.msg || '网络出错，请稍后注册！');
      }
    } else {
      ElMessage.error('网络出错，请稍后注册！');
    }
  }
}

</script>

<template>
  <div class="register-container">
    <div class="title">TestHub 测试开发平台</div>
    <div class="form-container">
      <h2 class="welcome-text">注册测试开发平台账号</h2>
      <el-form ref="registerFormRef" :model="registerForm" status-icon :rules="registerFormRules" label-width="auto"
               class="demo-registerForm">
        <!-- 用户名 -->
        <el-form-item prop="username" class="form-item">
          <el-icon color="#409efc" :size="30">
            <User />
          </el-icon>
          <el-input type="text" v-model="registerForm.username" placeholder="请输入用户名" />
        </el-form-item>

        <!-- 密码 -->
        <el-form-item prop="password" class="form-item">
          <el-icon color="#409efc" :size="30">
            <Lock />
          </el-icon>
          <el-input type="password" v-model="registerForm.password" placeholder="请输入密码" />
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item prop="email" class="form-item">
          <el-icon color="#409efc" :size="30">
            <Message />
          </el-icon>
          <el-input type="email" v-model="registerForm.email" placeholder="请输入邮箱" />
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item prop="phone_number" class="form-item">
          <el-icon color="#409efc" :size="30">
            <Iphone />
          </el-icon>
          <el-input type="text" v-model="registerForm.phone_number" placeholder="请输入手机号" />
        </el-form-item>

        <!-- 验证码 -->
        <el-form-item prop="code" class="form-item">
          <el-icon color="#409efc" :size="30">
            <Key />
          </el-icon>
          <el-input type="text" v-model="registerForm.code" placeholder="请输入验证码" />
          <el-button type="primary" @click="handleSendCode">发送验证码</el-button>
        </el-form-item>
        <!-- 用户类型 -->
        <el-form-item prop="user_type" class="form-item">
          <el-icon color="#409efc" :size="30">
            <UserFilled />
          </el-icon>
          <el-radio-group v-model="registerForm.user_type">
            <el-radio label="TESTER">测试工程师</el-radio>
            <el-radio label="DEVELOPER">开发工程师</el-radio>
            <el-radio label="MANAGER">测试管理员</el-radio>
            <el-radio label="VIEWER">报告查看者</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 登录链接 -->
        <p class="login-link-box">
          <router-link to="/login" class="login-link">已有账号？点击登录</router-link>
        </p>

        <!-- 注册按钮 -->
        <el-form-item id="button">
          <el-button type="primary" @click="submitForm(registerFormRef)">注册</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>


<style lang="less" scoped>
.register-container{
  background-image: url("@/assets/img/background.png");
  background-size: cover;
  background-attachment: fixed; /* 背景图固定，不随页面滚动 */
  min-height: 100vh;
}

.title {
  font-size: 35px;
  font-weight: bold;
  color: #ffffff;
  text-align: center;
}

.form-container {
  margin: auto;
  background: linear-gradient(135deg, #fff3e6, #f5f8fa);
  padding: 40px;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15); /* 更柔和的阴影 */
  width: 100%;
  max-width: 400px; /* 最大宽度 */
  transition: box-shadow 0.3s ease-in-out; /* 添加动态阴影效果 */
}

.form-container:hover {
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2); /* 鼠标悬停时阴影效果增强 */
}

.welcome-text {
  text-align: center;
  font-size: 1.5rem;
  margin-bottom: 30px;
  color: #333333;
}

.demo-registerForm {
  .form-item {
    display: flex;
    align-items: center;
    margin-bottom: 20px;

    .el-icon {
      margin-right: 10px; // 图标与输入框之间的间距
    }

    .el-input {
      flex: 1; // 输入框占据剩余空间
    }

    .el-radio-group {
      flex: 1; // 单选框组占据剩余空间
      display: flex;
      flex-wrap: wrap;
      gap: 10px; // 单选框之间的间距
    }
  }

  .el-input__inner {
    padding: 12px;
    font-size: 14px;
    border-radius: 4px;
    border: 1px solid #e0e0e0;
    transition: all 0.3s ease-in-out; /* 输入框过渡效果 */
  }

  .el-input__inner:focus {
    border-color: #409efc;
    box-shadow: 0 0 8px rgba(64, 158, 252, 0.3); /* 输入框聚焦时的光辉效果 */
    transform: scale(1.02); /* 聚焦时轻微放大 */
  }

  .el-icon {
    margin-right: 10px;
  }

  .login-link-box {
    text-align: center;
    margin-top: 10px;

    .login-link {
      color: #409efc;
      font-size: 14px;
      text-decoration: none;
      transition: color 0.3s ease; /* 过渡效果 */
    }

    .login-link:hover {
      text-decoration: underline;
      color: #2980b9; /* 鼠标悬停时颜色变更 */
    }
  }

  #button {
    text-align: center;
    .el-button {
      width: 100%;
      padding: 12px;
      font-size: 16px;
      border-radius: 4px;
      background: linear-gradient(45deg, #409efc, #1e74d8); /* 渐变背景 */
      border: none;
      transition: all 0.3s ease; /* 按钮过渡效果 */
    }

    .el-button:hover {
      background: linear-gradient(45deg, #1e74d8, #409efc);
      transform: scale(1.05); /* 鼠标悬停时按钮放大 */
      box-shadow: 0 4px 12px rgba(64, 158, 252, 0.3); /* 按钮悬停时阴影效果 */
    }
  }
}
</style>